#include "calc.h"
#include <cstdio>

Calc::Calc(const sptr<Adder> &adder)
{
    this->adder = adder;
}

int ParseInt(const std::string &expr)
{
    int value;
    int size = sscanf(expr.c_str(), "%d", &value);
    if (size == 1) {
        return value;
    } else {
        printf("cannot prase number in %s\n", expr.c_str());
        exit(1);
    }
}

int Calc::Parse(const std::string &exp)
{
    std::string expr = exp;
    int sum = ParseInt(expr);
    size_t found = expr.find('+');
    while (found != std::string::npos) {
        expr = expr.substr(found + 1);
        sum = adder->Sum(sum, ParseInt(expr));
        found = expr.find('+');
    }
    return sum;
}
